package com.example.friend.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.core.constants.CacheConstants;
import com.example.common.core.constants.Constants;
import com.example.common.core.enums.ExamListType;
import com.example.common.core.enums.ResultCode;
import com.example.common.redis.service.RedisService;
import com.example.common.security.exception.ServiceException;
import com.example.friend.domain.exam.Exam;
import com.example.friend.domain.exam.ExamQuestion;
import com.example.friend.domain.exam.dto.ExamQueryDTO;
import com.example.friend.domain.exam.vo.ExamVO;
import com.example.friend.domain.user.UserExam;
import com.example.friend.mapper.exam.ExamMapper;
import com.example.friend.mapper.exam.ExamQuestionMapper;
import com.example.friend.mapper.user.UserExamMapper;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class ExamCacheManager {
    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private ExamQuestionMapper examQuestionMapper;

    public Long getListSize(Integer examListType,Long userId) {
        String examListKey = getExamListKey(examListType, userId);
        //获取size
        return redisService.getListSize(examListKey);
    }


    public Long getExamQuestionSize(Long examId) {
        String examQuestionListKey = getExamQuestionListKey(examId);
        //获取size
        return redisService.getListSize(examQuestionListKey);
    }


    public List<ExamVO> getExamVOList(ExamQueryDTO examQueryDTO,Long userId) {
        //计算要分页查询的下标
        int start = (examQueryDTO.getPageNum() - 1) * examQueryDTO.getPageSize();
        int end = start + examQueryDTO.getPageSize() - 1; //下标需要 -1
        String examListKey = getExamListKey(examQueryDTO.getType(),userId);
        List<Long> examIdList = redisService.getCacheListByRange(examListKey, start, end, Long.class);
        List<ExamVO> examVOList = assembleExamVOList(examIdList);
        if (CollectionUtil.isEmpty(examVOList)) {
            //说明redis中数据可能有问题 从数据库中查数据并且重新刷新缓存
            examVOList = getExamListByDB(examQueryDTO,userId); //从数据库中获取数据
            refreshCache(examQueryDTO.getType(),userId); //在去刷新redis
        }
        return examVOList;
    }

    //获取用户所有报名竞赛id
    public List<Long> getAllUserExamList(Long userId) {
        String examListKey = CacheConstants.USER_EXAM_LIST + userId;
        List<Long> userExamIdList = redisService.getCacheListByRange(examListKey, 0, -1, Long.class);
        if(CollectionUtil.isNotEmpty(userExamIdList)){
            return userExamIdList;
        }
        //得去数据库查询
        List<UserExam> userExamList = userExamMapper.selectList(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getUserId,userId));
        if(CollectionUtil.isEmpty(userExamList)){
            return null;
        }
        //数据库中有数据,redis中无数据 --> 刷新redis
        refreshCache(ExamListType.USER_EXAM_LIST.getValue(), userId);
        return userExamList.stream().map(UserExam::getExamId).collect(Collectors.toList());
    }

    //获取竞赛的题目列表中第一道题目的id
    public Long getFirstQuestion(Long examId) {
        return redisService.indexForList(getExamQuestionListKey(examId), 0,Long.class);
    }

    //添加用户报名信息
    public void addUserExamCache(Long userId,Long examId) {
        String userExamListKey = getUserExamListKey(userId);
        //头插List
        redisService.leftPushForList(userExamListKey, examId);
    }

    //获取目标竞赛的上一题
    public Long preExamQuestion(Long examId, Long questionId) {
        //获取当前题目下标
        String examQuestionListKey = getExamQuestionListKey(examId);
        Long index = redisService.indexOfForList(examQuestionListKey,questionId);
        //检验
        if (index == 0) {
            throw new ServiceException(ResultCode.FAILED_FIRST_QUESTION);
        }
        return redisService.indexForList(examQuestionListKey,index - 1,Long.class);
    }

    //获取目标竞赛的下一题
    public Long nextExamQuestion(Long examId, Long questionId) {
        //获取当前题目下标
        String examQuestionListKey = getExamQuestionListKey(examId);
        Long index = redisService.indexOfForList(examQuestionListKey,questionId);
        //检验
        if (index == getExamQuestionSize(examId) - 1) {
            throw new ServiceException(ResultCode.FAILED_LAST_QUESTION);
        }
        return redisService.indexForList(examQuestionListKey,index + 1,Long.class);
    }

    //刷新缓存逻辑
    public void refreshCache(Integer examListType,Long userId) {
        List<Exam> examList = new ArrayList<>();
        //这里采用部分同步redis数据,当查询未完赛的redis中需要同步的时候,只针对未完赛的redis进行同步
        //不是所有的都进行同步(性能很差)
        if (ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(examListType)) {
            //查询未完赛的竞赛列表
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .gt(Exam::getEndTime, LocalDateTime.now())
                    .eq(Exam::getStatus, Constants.TRUE)
                    .orderByDesc(Exam::getCreateTime));
        } else if (ExamListType.EXAM_HISTORY_LIST.getValue().equals(examListType)) {
            //查询历史竞赛
            examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                    .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime, Exam::getEndTime)
                    .le(Exam::getEndTime, LocalDateTime.now())
                    .eq(Exam::getStatus, Constants.TRUE)
                    .orderByDesc(Exam::getCreateTime));
        } else if(ExamListType.USER_EXAM_LIST.getValue().equals(examListType)) {
            //我的竞赛列表
            List<ExamVO> examVOList = userExamMapper.selectUserExamList(userId);
            examList = BeanUtil.copyToList(examVOList, Exam.class);
        }
        if (CollectionUtil.isEmpty(examList)) {
            return;
        }

        Map<String, Exam> examMap = new HashMap<>();
        List<Long> examIdList = new ArrayList<>();
        for (Exam exam : examList) {
            examMap.put(getDetailKey(exam.getExamId()), exam);
            examIdList.add(exam.getExamId());
        }
        redisService.multiSet(examMap);  //刷新详情缓存
        redisService.deleteObject(getExamListKey(examListType,userId));
        redisService.rightPushAll(getExamListKey(examListType,userId), examIdList);      //刷新列表缓存
    }


    //维护ExamQuestionList
    public void refreshExamQuestionCache(Long examId) {
        List<ExamQuestion> examQuestionList = examQuestionMapper.selectList(new LambdaQueryWrapper<ExamQuestion>()
                        .select(ExamQuestion::getQuestionId)
                        .eq(ExamQuestion::getExamId, examId).orderByAsc(ExamQuestion::getCreateTime));
        if (CollectionUtil.isEmpty(examQuestionList)) {
            return;
        }
        List<Long> examQuestionIdList = examQuestionList.stream().map(ExamQuestion::getQuestionId).toList();
        //更新缓存 ---- 批量插入!!!!
        redisService.rightPushAll(getExamQuestionListKey(examId),examQuestionIdList);
        //节省 redis缓存资源
        long seconds = ChronoUnit.SECONDS.between(LocalDateTime.now(),
                LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0));
        redisService.expire(getExamQuestionListKey(examId), seconds, TimeUnit.SECONDS);
    }

    private List<ExamVO> getExamListByDB(ExamQueryDTO examQueryDTO,Long userId) {
        PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
        if (examQueryDTO.getType().equals(ExamListType.USER_EXAM_LIST.getValue())) {
            //我的竞赛列表数据查询
            return userExamMapper.selectUserExamList(userId);
        } else {
            //C端竞赛列表查询
            return examMapper.selectExamList(examQueryDTO);
        }
    }

    private List<ExamVO> assembleExamVOList(List<Long> examIdList) {
        if (CollectionUtil.isEmpty(examIdList)) {
            //说明redis当中没数据 从数据库中查数据并且重新刷新缓存
            return null;
        }
        //拼接redis当中key的方法 并且将拼接好的key存储到一个list中
        List<String> detailKeyList = new ArrayList<>();
        for (Long examId : examIdList) {
            detailKeyList.add(getDetailKey(examId));
        }
        List<ExamVO> examVOList = redisService.multiGet(detailKeyList, ExamVO.class);
        CollUtil.removeNull(examVOList);
        if (CollectionUtil.isEmpty(examVOList) || examVOList.size() != examIdList.size()) {
            //说明redis中数据有问题 从数据库中查数据并且重新刷新缓存
            return null;
        }
        return examVOList;
    }

    //key值转换
    private String getExamListKey(Integer examListType,Long userId) {
        if (ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(examListType)) {
            //未完赛
            return CacheConstants.EXAM_UNFINISHED_LIST;
        } else if (ExamListType.EXAM_HISTORY_LIST.getValue().equals(examListType)) {
            //已完赛
            return CacheConstants.EXAM_HISTORY_LIST;
        } else {
            //我的竞赛
            return CacheConstants.USER_EXAM_LIST + userId;
        }
    }


    private String getDetailKey(Long examId) {
        return CacheConstants.EXAM_DETAIL + examId;
    }

    private String getUserExamListKey(Long userId) {
        return CacheConstants.USER_EXAM_LIST + userId;
    }

    private String getExamQuestionListKey(Long examId) {
        return CacheConstants.EXAM_QUESTION_LIST + examId;
    }



}
